package com.qf.openapi2204.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qf.openapi2204.common.constants.RedisConstants;
import com.qf.openapi2204.common.vo.ResultVo;
import com.qf.openapi2204.zuul.feignclient.CacheClient;
import com.qf.openapi2204.zuul.localcache.LocalCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@Component
public class IdempotentFilter extends ZuulFilter {

    @Autowired
    CacheClient cacheClient;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 20;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        boolean result = currentContext.sendZuulResponse();
        HttpServletRequest request = currentContext.getRequest();
        String method = request.getParameter("method");
        // 需要参考匹配的路由信息中的 幂等性的配置
        HashMap<String, Object> map = LocalCache.routingCache.get(RedisConstants.APINAME_PREFIX + ":" + method);

        String idempotents = (String) map.get("idempotents");

        return result && idempotents.equals("1");
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String sign = request.getParameter("sign");

        //1. 检查是否重复提交了
        String prefix = RedisConstants.IDEMPOTENT_PRE;
        String id = sign;
        String key = prefix+":"+sign;
        ResultVo resultVo = cacheClient.get(key);

        Object data = resultVo.getData();
        if (data!=null){
            // 说明重复提交了，返回错误
            currentContext.setSendZuulResponse(false);

            HttpServletResponse response = currentContext.getResponse();
            response.setContentType("text/html;charset=utf-8");
            try {
                response.getWriter().println("重复提交请求了!");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 写入 redis
        cacheClient.set(key,key,100l);

        return null;
    }
}
